package handler

import (
	"encoding/json"
	"strconv"
	"time"
	"video-hub/cache"
	"video-hub/model"
	"video-hub/pkg"

	"github.com/gin-gonic/gin"
)

func UserLogin(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	redis_login_key := "redis_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()

	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次",
		})
		return
	}

	var user model.User
	err := model.DB.Where("username = ?", username).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询用户失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账户或密码错误",
		})
		return
	}

	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return

}

func UserAddRole(c *gin.Context) {

	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	data := model.UserRole{
		Uid: uid,
		Rid: rid,
	}

	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
	})
	return

}

func RoleAddNode(c *gin.Context) {

	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := model.UserRole{
		Uid: rid,
		Rid: nid,
	}

	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
	})
	return

}

func UserRoleList(c *gin.Context) {

	uid := c.Query("uid")
	//SELECT
	//*
	//	FROM
	//roles
	//LEFT JOIN user_roles ON user_roles.rid = roles.id
	//WHERE
	//user_roles.uid = 1

	var role []model.Role

	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid = ?", uid).
		Debug().
		Find(&role)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "Ok",
		"data": role,
	})
	return

}

func RoleNodeList(c *gin.Context) {

	rid := c.Query("rid")

	/**
	SELECT
	  *
	FROM
	  nodes
	  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
	WHERE
	  role_nodes.rid = 1
	*/

	var node []model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid = ?", rid).
		Debug().
		Find(&node)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "Ok",
		"data": node,
	})
	return

}

func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.PostForm("page"))
	size, _ := strconv.Atoi(c.PostForm("size"))
	offset := (page - 1) * size

	var user []model.User
	redis_list_key := "list_page_" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if result == "" {
		model.DB.Offset(offset).Limit(size).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	var total int64
	model.DB.Model(&model.User{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "Ok",
		"data":  user,
		"total": total,
	})

}

func Detail(c *gin.Context) {

	uid := c.Query("uid")

	var user []model.User
	redis_list_key := "list_detail_" + uid
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if result == "" {
		model.DB.Where("id = ?", uid).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "Ok",
		"data": user,
	})
	return

}
